package com.appkubes.mall.admin.application.system.attachment.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.appkubes.common.Response;
import com.appkubes.common.exception.BusinessException;
import com.appkubes.mall.admin.application.base.BaseController;
import com.appkubes.mall.admin.application.system.attachment.service.AttachmentGroupService;
import com.appkubes.mall.admin.application.system.attachment.service.AttachmentService;
import com.appkubes.mall.admin.utils.PageUtil;
import com.appkubes.mall.core.po.MallAttachment;
import com.appkubes.mall.core.po.MallAttachmentGroup;
import com.appkubes.storage.service.StorageService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

@Api(tags = "附件模块")
@RestController
@RequestMapping("/sass_admin/Sattachment")
public class AttachmentController extends BaseController {


    @Autowired
    AttachmentGroupService attachmentGroupService;

    @Autowired
    AttachmentService attachmentService;

    /*@Resource
    StorageService storageService;
    @Value("${ConfigValue.filePath}")
    String filePath;*/
    String endpoint = "oss-cn-beijing.aliyuncs.com";
    String accessKeyId = "LTAI4Fys7j3zyLzSZDnwvt8q";
    String accessKeySecret = "7vqMnoXB9WrxSkYBKtX5VX7l6K9oY7";
    String bucketName = "juxiong";

    /**
     * 添加分组
     *
     * @param model
     * @return
     */
    @ApiOperation(value = "添加分组")
    @PostMapping("/addGroup")
    public Response addGroup(MallAttachmentGroup model) {
        int result = 0;
        if (StringUtils.isEmpty(model.getAttachmentGroupKey())) model.setAttachmentGroupKey(null);
        if (!StringUtils.isEmpty(model.getAttachmentGroupKey())) {
            result = attachmentGroupService.update(model);
        } else {
            result = attachmentGroupService.add(model);
        }
        if (result > 0) {
            return Response.success(result);
        } else {
            return Response.error("保存失败");
        }
    }

    /**
     * 删除分组
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除分组")
    @PostMapping("/delGroup")
    public Response delGroup(@RequestParam String[] ids) {
        int result = attachmentGroupService.deleteByIds(ids);
        if (result > 0) {
            return Response.success(result);
        }
        return Response.error("删除失败");
    }

    /**
     * 图片列表
     *
     * @param key
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @ApiOperation(value = "图片列表")
    @PostMapping("/imageList")
    public Response getList(@RequestParam(defaultValue = "") String groupKey,
                            @RequestParam(defaultValue = "") String key,
                            @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer limit,
                            @RequestParam(defaultValue = "create_time") String sort,
                            @RequestParam(defaultValue = "desc") String order) {
        PageInfo<MallAttachment> pageinfo = attachmentService.querySelective(groupKey, key, page, limit, sort, order);
        for (MallAttachment model : pageinfo.getList()) {
            //model.setUrl(this.loadImg(model.getAttachment()));
        }
        return this.imgResponse(new PageUtil<MallAttachment>(pageinfo));
    }

    /**
     * 图片分组列表
     *
     * @param key
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @ApiOperation(value = "图片分组列表")
    @PostMapping("/groupList")
    public Response groupList(@RequestParam(defaultValue = "") String key,
                              @RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "100") Integer limit,
                              @RequestParam(defaultValue = "create_time") String sort,
                              @RequestParam(defaultValue = "desc") String order) {
        PageInfo<MallAttachmentGroup> pageinfo = attachmentGroupService.querySelective(key, page, limit, sort, order);
        return Response.success(new PageUtil<MallAttachmentGroup>(pageinfo));
    }

    /**
     * 删除图片
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除图片")
    @PostMapping("/delImage")
    public Response delImage(@RequestParam String ids) {
        int result = attachmentService.deleteByIds(ids.split(","));
        if (result > 0) {
            return Response.success(result);
        }
        return Response.error("删除失败");
    }


    @ApiOperation(value = "上传文件")
    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file,
                         @RequestParam(defaultValue = "0") String groupkey) {
        //替换成自己路径
        try {
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = null;
            try {
                //获取文件流
                inputStream = file.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取文件名称
            String filename = file.getOriginalFilename();
            //1.在文件名称中添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename = uuid+filename;

            //2.把文件按日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename = datePath +"/"+filename;
            System.out.println(filename+"较好的经济数据");

            //调用OSS方法实现上传
            ossClient.putObject(bucketName, filename, inputStream);
            ossClient.shutdown();
            //把上传之后的文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //路径规则：https://edu-cgq.oss-cn-chengdu.aliyuncs.com/QQ%E5%9B%BE%E7%89%8720200502111905.jpg
            MallAttachment model = new MallAttachment();
            model.setFilename(file.getOriginalFilename());
            model.setAttachment(filename);
            model.setType((byte) 1);
            model.setGroupKey(groupkey);
            attachmentService.add(model);
            return Response.success(model);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.error("文件上传失败");
        } finally {

        }
    }

}
